Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('data/dog_images/train')
valid_files, valid_targets = load_dataset('data/dog_images/valid')
test_files, test_targets = load_dataset('data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("data/dog_images/train/*/"))]
dog_breeds = len(dog_names)

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
/home/psenin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
# img = cv2.imread(human_files[13232])
img = cv2.imread(train_files[22])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
face_detected_counter = 0
ctr = 0
erroneous_faces_detections = []
for human_filename in human_files_short:
    if face_detector(human_filename):
        face_detected_counter = face_detected_counter + 1
    else:
        erroneous_faces_detections.append(ctr)
    ctr = ctr + 1    
print(" > detected " + str(face_detected_counter) + " faces out of " + str(len(human_files_short)) +
      ", i.e. " + "{0:.2f}%".format(face_detected_counter/len(human_files_short) * 100))
print(" > unable to detect faces at: ", erroneous_faces_detections)

face_detected_counter = 0
ctr = 0
erroneous_dogs_faces = []
for dog_filename in dog_files_short:
    if face_detector(dog_filename):
        face_detected_counter = face_detected_counter + 1
        erroneous_dogs_faces.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " human faces out of " + str(len(dog_files_short)) +
      " dog images, i.e. " + "{0:.2f}%".format(face_detected_counter/len(dog_files_short) * 100))
print(" > erroneous face predictions: ", erroneous_dogs_faces)
 > detected 99 faces out of 100, i.e. 99.00%
 > unable to detect faces at:  [88]
 > detected 12 human faces out of 100 dog images, i.e. 12.00%
 > erroneous face predictions:  [0, 14, 15, 21, 22, 23, 24, 30, 32, 37, 63, 78]
In [6]:
### see where it fails
import matplotlib.image as mpimg

def show_image(path):
    print("showing an image at " + path)
    img = mpimg.imread(path)
    plt.axis('off')
    imgplot = plt.imshow(img)
In [7]:
show_image(human_files_short[erroneous_faces_detections[0]])
showing an image at data/lfw/Angela_Bassett/Angela_Bassett_0003.jpg
In [8]:
show_image(dog_files_short[erroneous_dogs_faces[6]])
showing an image at data/dog_images/train/117.Pekingese/Pekingese_07559.jpg
In [9]:
### obviously -- there is a human!
show_image(dog_files_short[erroneous_dogs_faces[5]])
showing an image at data/dog_images/train/106.Newfoundland/Newfoundland_06989.jpg
In [10]:
face_detector(dog_files_short[erroneous_dogs_faces[5]])
Out[10]:
True

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [11]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Optional task: USING MTCNN for the human face detection

This addresses the Question 2 technically, because it can detect incomplete human faces as in example below and by tuning the certainty value I am getting less false positive. BUT, yes, I think asking a user to provide a more clear input is perfectly fine, it is a computer program we are working with, and it has its own potential quirks which might not be fixable in any easy way, making the user aware is good way to mitigate possible mistakes.

In addition, it is possible to look for eyes within a face rectangle -- if not found, then we can invalidate the face discovery.

In [12]:
from mtcnn.mtcnn import MTCNN
detector = MTCNN()

def face_detector2(img_path):
    img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
    
    ### MY LAPTOP'S gpu IS ONLY 4GB, it fails on large images
    height, width = img.shape[:2]
    if height > 1500 or width > 1500:
        img = cv2.resize(img, (0,0), fx=0.45, fy=0.45)
    height, width = img.shape[:2]
        
    ### yet another issue I saw is that some faces detected 
    ### by this implementation are really small bounding boxes
    ### so we filter by those, expecting a face to be at least 5% of the X or Y dimension
    intermediate_res = detector.detect_faces(img)
    res = []
    for idx in range(len(intermediate_res)):
        bounding_box = intermediate_res[idx]['box']
        if (bounding_box[2] > width/20 or bounding_box[3] > height/20) and\
           (intermediate_res[idx]['confidence'] > 0.978):
            res.append(bounding_box)
    
    return len(res) > 0
WARNING:tensorflow:From /home/psenin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/mtcnn/layer_factory.py:211: calling reduce_max (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
Instructions for updating:
keep_dims is deprecated, use keepdims instead
WARNING:tensorflow:From /home/psenin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/mtcnn/layer_factory.py:213: calling reduce_sum (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
Instructions for updating:
keep_dims is deprecated, use keepdims instead
In [13]:
img = cv2.cvtColor(cv2.imread(human_files_short[erroneous_faces_detections[0]]), cv2.COLOR_BGR2RGB)

res = detector.detect_faces(img)
bounding_box = res[0]['box']
keypoints = res[0]['keypoints']
print(res)
cv2.rectangle(img,
              (bounding_box[0], bounding_box[1]),
              (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),
              (0,155,255), 2)
bounding_box = res[1]['box']
keypoints = res[1]['keypoints']
cv2.rectangle(img,
              (bounding_box[0], bounding_box[1]),
              (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),
              (0,155,0), 2)
plt.imshow(img)
plt.show()
[{'box': [81, 71, 90, 114], 'confidence': 0.9997010827064514, 'keypoints': {'left_eye': (98, 116), 'right_eye': (138, 109), 'nose': (115, 140), 'mouth_left': (108, 155), 'mouth_right': (147, 150)}}, {'box': [-4, 75, 78, 118], 'confidence': 0.998508870601654, 'keypoints': {'left_eye': (10, 120), 'right_eye': (46, 125), 'nose': (18, 145), 'mouth_left': (6, 165), 'mouth_right': (38, 169)}}]

Test the OPTIONAL human face detector

In [14]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
face_detected_counter = 0
ctr = 0
erroneous_faces_detections = []
for human_filename in human_files_short:
    if face_detector2(human_filename):
        face_detected_counter = face_detected_counter + 1
    else:
        erroneous_faces_detections.append(ctr)
    ctr = ctr + 1    
print(" > detected " + str(face_detected_counter) + " faces out of " + str(len(human_files_short)) +
      ", i.e. " + "{0:.2f}%".format(face_detected_counter/len(human_files_short) * 100))
print(" > unable to detect faces at: ", erroneous_faces_detections)

face_detected_counter = 0
ctr = 0
erroneous_dogs_faces = []
for dog_filename in dog_files_short:
    if face_detector2(dog_filename):
        face_detected_counter = face_detected_counter + 1
        erroneous_dogs_faces.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " human faces out of " + str(len(dog_files_short)) +
      " dog images, i.e. " + "{0:.2f}%".format(face_detected_counter/len(dog_files_short) * 100))
print(" > erroneous face predictions: ", erroneous_dogs_faces)
 > detected 100 faces out of 100, i.e. 100.00%
 > unable to detect faces at:  []
 > detected 2 human faces out of 100 dog images, i.e. 2.00%
 > erroneous face predictions:  [23, 27]
In [15]:
img = cv2.cvtColor(cv2.imread(dog_files_short[erroneous_dogs_faces[1]]), cv2.COLOR_BGR2RGB)

res = detector.detect_faces(img)

height, width = img.shape[:2]

print(height, width)

for idx in range(len(res)):
    bounding_box = res[idx]['box']
    keypoints = res[idx]['keypoints']
    print(res[idx]['confidence'])
    cv2.rectangle(img,
              (bounding_box[0], bounding_box[1]),
              (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),
              (0,155,255), 2)
    print(bounding_box[2], bounding_box[3], height/20, bounding_box[3] > height/20)

plt.imshow(img)
plt.show()
297 500
0.99949049949646
50 57 14.85 True

OPTIONAL TASK Notes:

It seems like MTCNN technique is performing better but obviously more computationally expensive. Another good thing about this implementation is the ability to tune the cutoff for certainty of the face detection -- which enables to make better predictions, i.e. with less false positives.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [16]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [17]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [18]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))
In [19]:
show_image(train_files[22])
showing an image at data/dog_images/train/096.Labrador_retriever/Labrador_retriever_06474.jpg
In [20]:
# predicts 208, i.e. 208: 'Labrador retriever', https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a
ResNet50_predict_labels(train_files[22])
Out[20]:
208

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [21]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [22]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
dog_detected_counter = 0
ctr = 0
erroneous_dogs_in_humans = []
for human_filename in human_files_short:
    if dog_detector(human_filename):
        dog_detected_counter = dog_detected_counter + 1
        erroneous_dogs_in_humans.append(ctr)
    ctr = ctr + 1    
print(" > detected " + str(dog_detected_counter) + " dogs out of " + str(len(human_files_short)) +
      " human images, i.e. " + "{0:.2f}%".format(dog_detected_counter/len(human_files_short) * 100))
print(" > erroneous dog detection at: ", erroneous_dogs_in_humans)

dog_detected_counter = 0
ctr = 0
erroneous_dogs = []
for dog_filename in dog_files_short:
    if dog_detector(dog_filename):
        dog_detected_counter = dog_detected_counter + 1
    else:
        erroneous_dogs.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(dog_detected_counter) + " dog faces out of " + str(len(dog_files_short)) +
      " dog images, i.e. " + "{0:.2f}%".format(dog_detected_counter/len(dog_files_short) * 100))
print(" > can't detect dogs at: ", erroneous_dogs)
 > detected 1 dogs out of 100 human images, i.e. 1.00%
 > erroneous dog detection at:  [9]
 > detected 100 dog faces out of 100 dog images, i.e. 100.00%
 > can't detect dogs at:  []
In [23]:
### Oh, Fidel!
show_image(human_files_short[erroneous_dogs_in_humans[0]])
showing an image at data/lfw/Fidel_Castro/Fidel_Castro_0012.jpg

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [24]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:19<00:00, 84.51it/s]
100%|██████████| 835/835 [00:09<00:00, 90.65it/s]
100%|██████████| 836/836 [00:09<00:00, 85.83it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: I have used your design, with a minor modifications for strides and pooling. I found this configuration works a bit better. But it's just fiddling, I have no idea why its better. I tried different confiiguration, paddings, etc... Some of those increased the parameters count over 300K but there was a very small gain in the accuracy. I guess that really advanced networks are needed.

In [25]:
### TODO: Define your architecture.

from keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

img_width, img_height = 224, 224

model.add(Conv2D(filters = 16, kernel_size = (5,5), strides = (2,2), padding = 'valid', activation = 'relu',
                input_shape = (img_width, img_height, 3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5), strides = (3,3), padding = 'valid', activation = 'relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=None, padding='valid'))
model.add(Conv2D(filters = 64, kernel_size = (2,2), strides = (1,1), padding = 'valid', activation = 'relu'))
model.add(GlobalMaxPooling2D())
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(dog_breeds, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 110, 110, 16)      1216      
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 36, 36, 32)        12832     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 11, 11, 64)        8256      
_________________________________________________________________
global_max_pooling2d_1 (Glob (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 200)               13000     
_________________________________________________________________
dropout_1 (Dropout)          (None, 200)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               26733     
=================================================================
Total params: 62,037
Trainable params: 62,037
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [26]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [27]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 40

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6680/6680 [==============================] - 6s 930us/step - loss: 4.8836 - acc: 0.0096 - val_loss: 4.8695 - val_acc: 0.0132

Epoch 00001: val_loss improved from inf to 4.86951, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 2/40
6680/6680 [==============================] - 6s 827us/step - loss: 4.8619 - acc: 0.0123 - val_loss: 4.8419 - val_acc: 0.0120

Epoch 00002: val_loss improved from 4.86951 to 4.84192, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 3/40
6680/6680 [==============================] - 6s 829us/step - loss: 4.8127 - acc: 0.0202 - val_loss: 4.7495 - val_acc: 0.0192

Epoch 00003: val_loss improved from 4.84192 to 4.74951, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 4/40
6680/6680 [==============================] - 5s 804us/step - loss: 4.7215 - acc: 0.0220 - val_loss: 4.6514 - val_acc: 0.0240

Epoch 00004: val_loss improved from 4.74951 to 4.65143, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 5/40
6680/6680 [==============================] - 5s 805us/step - loss: 4.6006 - acc: 0.0325 - val_loss: 4.5254 - val_acc: 0.0371

Epoch 00005: val_loss improved from 4.65143 to 4.52538, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 6/40
6680/6680 [==============================] - 5s 792us/step - loss: 4.4552 - acc: 0.0395 - val_loss: 4.3699 - val_acc: 0.0599

Epoch 00006: val_loss improved from 4.52538 to 4.36985, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 7/40
6680/6680 [==============================] - 5s 795us/step - loss: 4.3051 - acc: 0.0555 - val_loss: 4.3271 - val_acc: 0.0563

Epoch 00007: val_loss improved from 4.36985 to 4.32709, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 8/40
6680/6680 [==============================] - 5s 801us/step - loss: 4.1782 - acc: 0.0677 - val_loss: 4.1490 - val_acc: 0.0695

Epoch 00008: val_loss improved from 4.32709 to 4.14896, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 9/40
6680/6680 [==============================] - 5s 798us/step - loss: 4.0700 - acc: 0.0751 - val_loss: 4.1231 - val_acc: 0.0802

Epoch 00009: val_loss improved from 4.14896 to 4.12311, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 10/40
6680/6680 [==============================] - 5s 806us/step - loss: 3.9763 - acc: 0.0898 - val_loss: 3.9974 - val_acc: 0.0778

Epoch 00010: val_loss improved from 4.12311 to 3.99745, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 11/40
6680/6680 [==============================] - 5s 807us/step - loss: 3.8845 - acc: 0.0963 - val_loss: 4.0295 - val_acc: 0.0862

Epoch 00011: val_loss did not improve from 3.99745
Epoch 12/40
6680/6680 [==============================] - 5s 796us/step - loss: 3.8177 - acc: 0.1102 - val_loss: 4.1209 - val_acc: 0.0946

Epoch 00012: val_loss did not improve from 3.99745
Epoch 13/40
6680/6680 [==============================] - 5s 790us/step - loss: 3.7299 - acc: 0.1169 - val_loss: 3.8856 - val_acc: 0.0958

Epoch 00013: val_loss improved from 3.99745 to 3.88559, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 14/40
6680/6680 [==============================] - 5s 791us/step - loss: 3.6532 - acc: 0.1307 - val_loss: 3.9071 - val_acc: 0.1030

Epoch 00014: val_loss did not improve from 3.88559
Epoch 15/40
6680/6680 [==============================] - 5s 803us/step - loss: 3.5723 - acc: 0.1403 - val_loss: 4.1084 - val_acc: 0.0910

Epoch 00015: val_loss did not improve from 3.88559
Epoch 16/40
6680/6680 [==============================] - 5s 796us/step - loss: 3.5138 - acc: 0.1513 - val_loss: 3.9557 - val_acc: 0.0922

Epoch 00016: val_loss did not improve from 3.88559
Epoch 17/40
6680/6680 [==============================] - 5s 794us/step - loss: 3.4562 - acc: 0.1587 - val_loss: 3.8398 - val_acc: 0.1174

Epoch 00017: val_loss improved from 3.88559 to 3.83983, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 18/40
6680/6680 [==============================] - 5s 794us/step - loss: 3.4024 - acc: 0.1728 - val_loss: 3.8339 - val_acc: 0.1186

Epoch 00018: val_loss improved from 3.83983 to 3.83386, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 19/40
6680/6680 [==============================] - 5s 792us/step - loss: 3.3202 - acc: 0.1838 - val_loss: 3.8601 - val_acc: 0.1257

Epoch 00019: val_loss did not improve from 3.83386
Epoch 20/40
6680/6680 [==============================] - 5s 796us/step - loss: 3.2852 - acc: 0.1817 - val_loss: 3.8501 - val_acc: 0.1186

Epoch 00020: val_loss did not improve from 3.83386
Epoch 21/40
6680/6680 [==============================] - 5s 794us/step - loss: 3.2274 - acc: 0.1936 - val_loss: 3.9004 - val_acc: 0.1210

Epoch 00021: val_loss did not improve from 3.83386
Epoch 22/40
6680/6680 [==============================] - 5s 792us/step - loss: 3.1881 - acc: 0.2058 - val_loss: 3.8307 - val_acc: 0.1269

Epoch 00022: val_loss improved from 3.83386 to 3.83066, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 23/40
6680/6680 [==============================] - 5s 794us/step - loss: 3.1251 - acc: 0.2175 - val_loss: 3.9014 - val_acc: 0.1317

Epoch 00023: val_loss did not improve from 3.83066
Epoch 24/40
6680/6680 [==============================] - 5s 793us/step - loss: 3.0972 - acc: 0.2256 - val_loss: 4.0021 - val_acc: 0.1293

Epoch 00024: val_loss did not improve from 3.83066
Epoch 25/40
6680/6680 [==============================] - 5s 792us/step - loss: 3.0364 - acc: 0.2249 - val_loss: 4.0623 - val_acc: 0.1365

Epoch 00025: val_loss did not improve from 3.83066
Epoch 26/40
6680/6680 [==============================] - 5s 793us/step - loss: 3.0268 - acc: 0.2305 - val_loss: 3.8609 - val_acc: 0.1389

Epoch 00026: val_loss did not improve from 3.83066
Epoch 27/40
6680/6680 [==============================] - 5s 798us/step - loss: 2.9510 - acc: 0.2461 - val_loss: 3.9201 - val_acc: 0.1437

Epoch 00027: val_loss did not improve from 3.83066
Epoch 28/40
6680/6680 [==============================] - 5s 792us/step - loss: 2.9234 - acc: 0.2510 - val_loss: 4.0410 - val_acc: 0.1413

Epoch 00028: val_loss did not improve from 3.83066
Epoch 29/40
6680/6680 [==============================] - 5s 798us/step - loss: 2.8966 - acc: 0.2582 - val_loss: 3.8725 - val_acc: 0.1389

Epoch 00029: val_loss did not improve from 3.83066
Epoch 30/40
6680/6680 [==============================] - 5s 797us/step - loss: 2.8281 - acc: 0.2696 - val_loss: 3.9632 - val_acc: 0.1353

Epoch 00030: val_loss did not improve from 3.83066
Epoch 31/40
6680/6680 [==============================] - 5s 803us/step - loss: 2.8207 - acc: 0.2751 - val_loss: 4.1199 - val_acc: 0.1473

Epoch 00031: val_loss did not improve from 3.83066
Epoch 32/40
6680/6680 [==============================] - 5s 792us/step - loss: 2.7616 - acc: 0.2811 - val_loss: 3.9480 - val_acc: 0.1497

Epoch 00032: val_loss did not improve from 3.83066
Epoch 33/40
6680/6680 [==============================] - 5s 797us/step - loss: 2.7515 - acc: 0.2810 - val_loss: 4.0323 - val_acc: 0.1617

Epoch 00033: val_loss did not improve from 3.83066
Epoch 34/40
6680/6680 [==============================] - 5s 790us/step - loss: 2.7224 - acc: 0.2958 - val_loss: 4.0340 - val_acc: 0.1281

Epoch 00034: val_loss did not improve from 3.83066
Epoch 35/40
6680/6680 [==============================] - 5s 789us/step - loss: 2.6866 - acc: 0.2946 - val_loss: 4.0469 - val_acc: 0.1341

Epoch 00035: val_loss did not improve from 3.83066
Epoch 36/40
6680/6680 [==============================] - 5s 792us/step - loss: 2.6579 - acc: 0.3031 - val_loss: 4.2680 - val_acc: 0.1413

Epoch 00036: val_loss did not improve from 3.83066
Epoch 37/40
6680/6680 [==============================] - 5s 788us/step - loss: 2.6425 - acc: 0.3045 - val_loss: 4.1068 - val_acc: 0.1353

Epoch 00037: val_loss did not improve from 3.83066
Epoch 38/40
6680/6680 [==============================] - 5s 788us/step - loss: 2.6048 - acc: 0.3147 - val_loss: 4.0079 - val_acc: 0.1401

Epoch 00038: val_loss did not improve from 3.83066
Epoch 39/40
6680/6680 [==============================] - 5s 802us/step - loss: 2.5695 - acc: 0.3220 - val_loss: 4.3928 - val_acc: 0.1305

Epoch 00039: val_loss did not improve from 3.83066
Epoch 40/40
6680/6680 [==============================] - 5s 797us/step - loss: 2.5646 - acc: 0.3216 - val_loss: 4.2046 - val_acc: 0.1246

Epoch 00040: val_loss did not improve from 3.83066
Out[27]:
<keras.callbacks.History at 0x7f077c08d6a0>

Load the Model with the Best Validation Loss

In [28]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [29]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 11.4833%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [30]:
bottleneck_features = np.load('data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [31]:
from keras.layers import GlobalAveragePooling2D

VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [32]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [87]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=50, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
6680/6680 [==============================] - 3s 481us/step - loss: 5.8087 - acc: 0.6385 - val_loss: 6.8920 - val_acc: 0.5102

Epoch 00001: val_loss improved from inf to 6.89202, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/50
6680/6680 [==============================] - 3s 482us/step - loss: 5.8084 - acc: 0.6380 - val_loss: 6.8445 - val_acc: 0.5054

Epoch 00002: val_loss improved from 6.89202 to 6.84446, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/50
6680/6680 [==============================] - 3s 487us/step - loss: 5.8050 - acc: 0.6383 - val_loss: 6.8461 - val_acc: 0.5138

Epoch 00003: val_loss did not improve from 6.84446
Epoch 4/50
6680/6680 [==============================] - 3s 488us/step - loss: 5.8033 - acc: 0.6382 - val_loss: 6.8854 - val_acc: 0.5126

Epoch 00004: val_loss did not improve from 6.84446
Epoch 5/50
6680/6680 [==============================] - 3s 485us/step - loss: 5.7756 - acc: 0.6359 - val_loss: 6.7704 - val_acc: 0.5090

Epoch 00005: val_loss improved from 6.84446 to 6.77037, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 6/50
6680/6680 [==============================] - 3s 489us/step - loss: 5.7114 - acc: 0.6388 - val_loss: 6.9686 - val_acc: 0.4934

Epoch 00006: val_loss did not improve from 6.77037
Epoch 7/50
6680/6680 [==============================] - 3s 485us/step - loss: 5.6430 - acc: 0.6422 - val_loss: 6.9599 - val_acc: 0.4934

Epoch 00007: val_loss did not improve from 6.77037
Epoch 8/50
6680/6680 [==============================] - 3s 490us/step - loss: 5.6061 - acc: 0.6466 - val_loss: 6.7942 - val_acc: 0.5102

Epoch 00008: val_loss did not improve from 6.77037
Epoch 9/50
6680/6680 [==============================] - 3s 489us/step - loss: 5.5894 - acc: 0.6490 - val_loss: 6.8669 - val_acc: 0.5042

Epoch 00009: val_loss did not improve from 6.77037
Epoch 10/50
6680/6680 [==============================] - 3s 489us/step - loss: 5.5841 - acc: 0.6499 - val_loss: 6.7825 - val_acc: 0.5102

Epoch 00010: val_loss did not improve from 6.77037
Epoch 11/50
6680/6680 [==============================] - 3s 491us/step - loss: 5.5746 - acc: 0.6522 - val_loss: 6.8014 - val_acc: 0.5030

Epoch 00011: val_loss did not improve from 6.77037
Epoch 12/50
6680/6680 [==============================] - 3s 497us/step - loss: 5.5707 - acc: 0.6525 - val_loss: 6.7643 - val_acc: 0.5066

Epoch 00012: val_loss improved from 6.77037 to 6.76431, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 13/50
6680/6680 [==============================] - 3s 493us/step - loss: 5.5706 - acc: 0.6524 - val_loss: 6.8097 - val_acc: 0.5102

Epoch 00013: val_loss did not improve from 6.76431
Epoch 14/50
6680/6680 [==============================] - 3s 490us/step - loss: 5.5706 - acc: 0.6531 - val_loss: 6.7875 - val_acc: 0.5102

Epoch 00014: val_loss did not improve from 6.76431
Epoch 15/50
6680/6680 [==============================] - 3s 490us/step - loss: 5.5696 - acc: 0.6527 - val_loss: 6.7782 - val_acc: 0.5102

Epoch 00015: val_loss did not improve from 6.76431
Epoch 16/50
6680/6680 [==============================] - 3s 487us/step - loss: 5.5689 - acc: 0.6528 - val_loss: 6.8320 - val_acc: 0.4982

Epoch 00016: val_loss did not improve from 6.76431
Epoch 17/50
6680/6680 [==============================] - 3s 490us/step - loss: 5.5593 - acc: 0.6522 - val_loss: 6.7942 - val_acc: 0.4958

Epoch 00017: val_loss did not improve from 6.76431
Epoch 18/50
6680/6680 [==============================] - 3s 491us/step - loss: 5.4911 - acc: 0.6533 - val_loss: 6.7373 - val_acc: 0.5102

Epoch 00018: val_loss improved from 6.76431 to 6.73727, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 19/50
6680/6680 [==============================] - 3s 501us/step - loss: 5.4456 - acc: 0.6575 - val_loss: 6.7248 - val_acc: 0.5210

Epoch 00019: val_loss improved from 6.73727 to 6.72477, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 20/50
6680/6680 [==============================] - 3s 486us/step - loss: 5.4251 - acc: 0.6590 - val_loss: 6.6834 - val_acc: 0.5162

Epoch 00020: val_loss improved from 6.72477 to 6.68343, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 21/50
6680/6680 [==============================] - 3s 488us/step - loss: 5.4037 - acc: 0.6605 - val_loss: 6.8270 - val_acc: 0.5042

Epoch 00021: val_loss did not improve from 6.68343
Epoch 22/50
6680/6680 [==============================] - 3s 492us/step - loss: 5.2974 - acc: 0.6594 - val_loss: 6.6561 - val_acc: 0.5114

Epoch 00022: val_loss improved from 6.68343 to 6.65606, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 23/50
6680/6680 [==============================] - 3s 493us/step - loss: 5.1760 - acc: 0.6699 - val_loss: 6.5178 - val_acc: 0.5269

Epoch 00023: val_loss improved from 6.65606 to 6.51779, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 24/50
6680/6680 [==============================] - 3s 492us/step - loss: 5.0659 - acc: 0.6746 - val_loss: 6.5294 - val_acc: 0.5150

Epoch 00024: val_loss did not improve from 6.51779
Epoch 25/50
6680/6680 [==============================] - 3s 489us/step - loss: 5.0127 - acc: 0.6829 - val_loss: 6.4559 - val_acc: 0.5269

Epoch 00025: val_loss improved from 6.51779 to 6.45590, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 26/50
6680/6680 [==============================] - 3s 490us/step - loss: 4.9948 - acc: 0.6834 - val_loss: 6.4151 - val_acc: 0.5222

Epoch 00026: val_loss improved from 6.45590 to 6.41515, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 27/50
6680/6680 [==============================] - 3s 500us/step - loss: 4.9807 - acc: 0.6871 - val_loss: 6.4382 - val_acc: 0.5269

Epoch 00027: val_loss did not improve from 6.41515
Epoch 28/50
6680/6680 [==============================] - 3s 495us/step - loss: 4.9738 - acc: 0.6880 - val_loss: 6.4748 - val_acc: 0.5234

Epoch 00028: val_loss did not improve from 6.41515
Epoch 29/50
6680/6680 [==============================] - 3s 503us/step - loss: 4.9738 - acc: 0.6883 - val_loss: 6.4297 - val_acc: 0.5246

Epoch 00029: val_loss did not improve from 6.41515
Epoch 30/50
6680/6680 [==============================] - 3s 500us/step - loss: 4.9729 - acc: 0.6897 - val_loss: 6.4249 - val_acc: 0.5257

Epoch 00030: val_loss did not improve from 6.41515
Epoch 31/50
6680/6680 [==============================] - 3s 501us/step - loss: 4.9720 - acc: 0.6894 - val_loss: 6.5159 - val_acc: 0.5210

Epoch 00031: val_loss did not improve from 6.41515
Epoch 32/50
6680/6680 [==============================] - 3s 496us/step - loss: 4.9694 - acc: 0.6898 - val_loss: 6.3989 - val_acc: 0.5365

Epoch 00032: val_loss improved from 6.41515 to 6.39888, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 33/50
6680/6680 [==============================] - 3s 501us/step - loss: 4.9657 - acc: 0.6906 - val_loss: 6.4554 - val_acc: 0.5329

Epoch 00033: val_loss did not improve from 6.39888
Epoch 34/50
6680/6680 [==============================] - 3s 497us/step - loss: 4.9672 - acc: 0.6901 - val_loss: 6.4368 - val_acc: 0.5293

Epoch 00034: val_loss did not improve from 6.39888
Epoch 35/50
6680/6680 [==============================] - 3s 498us/step - loss: 4.9664 - acc: 0.6909 - val_loss: 6.4396 - val_acc: 0.5329

Epoch 00035: val_loss did not improve from 6.39888
Epoch 36/50
6680/6680 [==============================] - 3s 496us/step - loss: 4.9658 - acc: 0.6907 - val_loss: 6.4077 - val_acc: 0.5317

Epoch 00036: val_loss did not improve from 6.39888
Epoch 37/50
6680/6680 [==============================] - 3s 502us/step - loss: 4.9655 - acc: 0.6909 - val_loss: 6.4090 - val_acc: 0.5353

Epoch 00037: val_loss did not improve from 6.39888
Epoch 38/50
6680/6680 [==============================] - 3s 495us/step - loss: 4.9644 - acc: 0.6909 - val_loss: 6.4678 - val_acc: 0.5222

Epoch 00038: val_loss did not improve from 6.39888
Epoch 39/50
6680/6680 [==============================] - 3s 497us/step - loss: 4.9645 - acc: 0.6912 - val_loss: 6.4129 - val_acc: 0.5257

Epoch 00039: val_loss did not improve from 6.39888
Epoch 40/50
6680/6680 [==============================] - 3s 489us/step - loss: 4.9461 - acc: 0.6901 - val_loss: 6.5875 - val_acc: 0.5114

Epoch 00040: val_loss did not improve from 6.39888
Epoch 41/50
6680/6680 [==============================] - 3s 489us/step - loss: 4.8860 - acc: 0.6934 - val_loss: 6.4134 - val_acc: 0.5365

Epoch 00041: val_loss did not improve from 6.39888
Epoch 42/50
6680/6680 [==============================] - 3s 487us/step - loss: 4.8633 - acc: 0.6943 - val_loss: 6.3531 - val_acc: 0.5329

Epoch 00042: val_loss improved from 6.39888 to 6.35313, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 43/50
6680/6680 [==============================] - 3s 496us/step - loss: 4.8537 - acc: 0.6967 - val_loss: 6.3681 - val_acc: 0.5246

Epoch 00043: val_loss did not improve from 6.35313
Epoch 44/50
6680/6680 [==============================] - 3s 485us/step - loss: 4.8322 - acc: 0.6946 - val_loss: 6.4813 - val_acc: 0.5150

Epoch 00044: val_loss did not improve from 6.35313
Epoch 45/50
6680/6680 [==============================] - 3s 490us/step - loss: 4.7472 - acc: 0.7004 - val_loss: 6.2988 - val_acc: 0.5413

Epoch 00045: val_loss improved from 6.35313 to 6.29876, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 46/50
6680/6680 [==============================] - 3s 486us/step - loss: 4.7261 - acc: 0.7034 - val_loss: 6.2471 - val_acc: 0.5401

Epoch 00046: val_loss improved from 6.29876 to 6.24710, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 47/50
6680/6680 [==============================] - 3s 488us/step - loss: 4.7080 - acc: 0.7042 - val_loss: 6.1921 - val_acc: 0.5461

Epoch 00047: val_loss improved from 6.24710 to 6.19210, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 48/50
6680/6680 [==============================] - 3s 487us/step - loss: 4.6547 - acc: 0.7060 - val_loss: 6.1860 - val_acc: 0.5473

Epoch 00048: val_loss improved from 6.19210 to 6.18598, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 49/50
6680/6680 [==============================] - 3s 490us/step - loss: 4.6144 - acc: 0.7106 - val_loss: 6.1782 - val_acc: 0.5425

Epoch 00049: val_loss improved from 6.18598 to 6.17815, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 50/50
6680/6680 [==============================] - 3s 489us/step - loss: 4.6016 - acc: 0.7129 - val_loss: 6.1310 - val_acc: 0.5545

Epoch 00050: val_loss improved from 6.17815 to 6.13096, saving model to saved_models/weights.best.VGG16.hdf5
Out[87]:
<keras.callbacks.History at 0x7fc02fe37dd8>

Load the Model with the Best Validation Loss

In [88]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [89]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 54.5455%

Predict Dog Breed with the Model

In [94]:
from extract_bottleneck_features import *

# top_N defines how many predictions to return
top_N = 3

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    prediction = predicted_vector[0]
    
    breeds_predicted = [dog_names[idx] for idx in np.argsort(prediction)[::-1][:top_N]]
    confidence_predicted = np.sort(prediction)[::-1][:top_N]
    
    # return dog breed that is predicted by the model
    return breeds_predicted, confidence_predicted
In [95]:
VGG16_predict_breed(train_files[2])
Out[95]:
(['n/088.Irish_water_spaniel', 'n/053.Cocker_spaniel', 'n/124.Poodle'],
 array([1.0000000e+00, 6.5827965e-09, 2.1614623e-10], dtype=float32))
In [96]:
show_image(train_files[2])
showing an image at data/dog_images/train/088.Irish_water_spaniel/Irish_water_spaniel_06014.jpg

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [78]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('data/bottleneck_features/DogInceptionV3Data.npz')
train_inceptionv3 = bottleneck_features['train']
valid_inceptionv3 = bottleneck_features['valid']
test_inceptionv3 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: I found that Inception performs much better than VGG-16 and just used it. So, it is an experimental evaluation which set me on this path. Personally, it's difficult for me to tell why exactly Inception outperforms the VGG net. It could be that it trains much slower (a mentions about this I found at few places) and more epochs and images are required to achieve a better performance. It could also be that Inception is just suited better for this task as it combines multiple (sized differently) convolutions within the same module, thus having a better grasp on distinct dog breed features.

I tried different batch sizes and numbers of epochs. From my experience this changes the classification results, sometimes they are getting really bad in real case predictions. Who would guess that it can be so unstable, I mean sensitive.

In [79]:
### TODO: Define your architecture.
from keras.layers import GlobalMaxPooling2D

InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalMaxPooling2D(input_shape=train_inceptionv3.shape[1:]))
InceptionV3_model.add(Dense(133, activation='softmax'))

InceptionV3_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_max_pooling2d_3 (Glob (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [80]:
### TODO: Compile the model.
InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [84]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_model.fit(train_inceptionv3, train_targets, 
          validation_data=(valid_inceptionv3, valid_targets),
          epochs=60, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/60
6680/6680 [==============================] - 4s 541us/step - loss: 1.2190 - acc: 0.9214 - val_loss: 2.3519 - val_acc: 0.7892

Epoch 00001: val_loss improved from inf to 2.35187, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 2/60
6680/6680 [==============================] - 4s 549us/step - loss: 1.2156 - acc: 0.9211 - val_loss: 2.3892 - val_acc: 0.7940

Epoch 00002: val_loss did not improve from 2.35187
Epoch 3/60
6680/6680 [==============================] - 4s 539us/step - loss: 1.1924 - acc: 0.9216 - val_loss: 2.2601 - val_acc: 0.7964

Epoch 00003: val_loss improved from 2.35187 to 2.26013, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 4/60
6680/6680 [==============================] - 4s 544us/step - loss: 1.0625 - acc: 0.9238 - val_loss: 2.0884 - val_acc: 0.8036

Epoch 00004: val_loss improved from 2.26013 to 2.08845, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 5/60
6680/6680 [==============================] - 4s 548us/step - loss: 0.9355 - acc: 0.9337 - val_loss: 2.2232 - val_acc: 0.8036

Epoch 00005: val_loss did not improve from 2.08845
Epoch 6/60
6680/6680 [==============================] - 4s 552us/step - loss: 0.9156 - acc: 0.9364 - val_loss: 2.1039 - val_acc: 0.8216

Epoch 00006: val_loss did not improve from 2.08845
Epoch 7/60
6680/6680 [==============================] - 4s 549us/step - loss: 0.9094 - acc: 0.9386 - val_loss: 2.1072 - val_acc: 0.8204

Epoch 00007: val_loss did not improve from 2.08845
Epoch 8/60
6680/6680 [==============================] - 4s 566us/step - loss: 0.9004 - acc: 0.9401 - val_loss: 2.0363 - val_acc: 0.8108

Epoch 00008: val_loss improved from 2.08845 to 2.03629, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 9/60
6680/6680 [==============================] - 4s 573us/step - loss: 0.8967 - acc: 0.9418 - val_loss: 2.0579 - val_acc: 0.8180

Epoch 00009: val_loss did not improve from 2.03629
Epoch 10/60
6680/6680 [==============================] - 4s 551us/step - loss: 0.8929 - acc: 0.9404 - val_loss: 2.1994 - val_acc: 0.8072

Epoch 00010: val_loss did not improve from 2.03629
Epoch 11/60
6680/6680 [==============================] - 3s 506us/step - loss: 0.8888 - acc: 0.9422 - val_loss: 2.1712 - val_acc: 0.8072

Epoch 00011: val_loss did not improve from 2.03629
Epoch 12/60
6680/6680 [==============================] - 4s 584us/step - loss: 0.8896 - acc: 0.9427 - val_loss: 2.0861 - val_acc: 0.8084

Epoch 00012: val_loss did not improve from 2.03629
Epoch 13/60
6680/6680 [==============================] - 4s 579us/step - loss: 0.8830 - acc: 0.9430 - val_loss: 2.1743 - val_acc: 0.8096

Epoch 00013: val_loss did not improve from 2.03629
Epoch 14/60
6680/6680 [==============================] - 4s 542us/step - loss: 0.8834 - acc: 0.9433 - val_loss: 2.0405 - val_acc: 0.8144

Epoch 00014: val_loss did not improve from 2.03629
Epoch 15/60
6680/6680 [==============================] - 4s 579us/step - loss: 0.8824 - acc: 0.9431 - val_loss: 2.1781 - val_acc: 0.8108

Epoch 00015: val_loss did not improve from 2.03629
Epoch 16/60
6680/6680 [==============================] - 4s 537us/step - loss: 0.8809 - acc: 0.9436 - val_loss: 2.0679 - val_acc: 0.8132

Epoch 00016: val_loss did not improve from 2.03629
Epoch 17/60
6680/6680 [==============================] - 3s 508us/step - loss: 0.8796 - acc: 0.9442 - val_loss: 2.0951 - val_acc: 0.8216

Epoch 00017: val_loss did not improve from 2.03629
Epoch 18/60
6680/6680 [==============================] - 3s 507us/step - loss: 0.8803 - acc: 0.9440 - val_loss: 2.1011 - val_acc: 0.8180

Epoch 00018: val_loss did not improve from 2.03629
Epoch 19/60
6680/6680 [==============================] - 3s 514us/step - loss: 0.8810 - acc: 0.9439 - val_loss: 2.0226 - val_acc: 0.8287

Epoch 00019: val_loss improved from 2.03629 to 2.02256, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 20/60
6680/6680 [==============================] - 3s 507us/step - loss: 0.8812 - acc: 0.9442 - val_loss: 2.0878 - val_acc: 0.8156

Epoch 00020: val_loss did not improve from 2.02256
Epoch 21/60
6680/6680 [==============================] - 3s 508us/step - loss: 0.8777 - acc: 0.9446 - val_loss: 2.0883 - val_acc: 0.8240

Epoch 00021: val_loss did not improve from 2.02256
Epoch 22/60
6680/6680 [==============================] - 4s 529us/step - loss: 0.8829 - acc: 0.9446 - val_loss: 2.0438 - val_acc: 0.8204

Epoch 00022: val_loss did not improve from 2.02256
Epoch 23/60
6680/6680 [==============================] - 4s 547us/step - loss: 0.8809 - acc: 0.9442 - val_loss: 2.0122 - val_acc: 0.8084

Epoch 00023: val_loss improved from 2.02256 to 2.01224, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 24/60
6680/6680 [==============================] - 4s 525us/step - loss: 0.8773 - acc: 0.9442 - val_loss: 2.0083 - val_acc: 0.8180

Epoch 00024: val_loss improved from 2.01224 to 2.00829, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 25/60
6680/6680 [==============================] - 3s 513us/step - loss: 0.8795 - acc: 0.9448 - val_loss: 2.0860 - val_acc: 0.8216

Epoch 00025: val_loss did not improve from 2.00829
Epoch 26/60
6680/6680 [==============================] - 3s 508us/step - loss: 0.8806 - acc: 0.9443 - val_loss: 2.1048 - val_acc: 0.8251

Epoch 00026: val_loss did not improve from 2.00829
Epoch 27/60
6680/6680 [==============================] - 3s 510us/step - loss: 0.8785 - acc: 0.9445 - val_loss: 2.1178 - val_acc: 0.8216

Epoch 00027: val_loss did not improve from 2.00829
Epoch 28/60
6680/6680 [==============================] - 4s 531us/step - loss: 0.8772 - acc: 0.9448 - val_loss: 2.1198 - val_acc: 0.8204

Epoch 00028: val_loss did not improve from 2.00829
Epoch 29/60
6680/6680 [==============================] - 4s 528us/step - loss: 0.8799 - acc: 0.9443 - val_loss: 2.1582 - val_acc: 0.8120

Epoch 00029: val_loss did not improve from 2.00829
Epoch 30/60
6680/6680 [==============================] - 4s 539us/step - loss: 0.8802 - acc: 0.9448 - val_loss: 2.0623 - val_acc: 0.8240

Epoch 00030: val_loss did not improve from 2.00829
Epoch 31/60
6680/6680 [==============================] - 4s 529us/step - loss: 0.8760 - acc: 0.9449 - val_loss: 2.1245 - val_acc: 0.8168

Epoch 00031: val_loss did not improve from 2.00829
Epoch 32/60
6680/6680 [==============================] - 4s 534us/step - loss: 0.8806 - acc: 0.9445 - val_loss: 2.0190 - val_acc: 0.8251

Epoch 00032: val_loss did not improve from 2.00829
Epoch 33/60
6680/6680 [==============================] - 3s 514us/step - loss: 0.8784 - acc: 0.9446 - val_loss: 2.0061 - val_acc: 0.8216

Epoch 00033: val_loss improved from 2.00829 to 2.00610, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 34/60
6680/6680 [==============================] - 4s 550us/step - loss: 0.8788 - acc: 0.9445 - val_loss: 2.0766 - val_acc: 0.8228

Epoch 00034: val_loss did not improve from 2.00610
Epoch 35/60
6680/6680 [==============================] - 4s 577us/step - loss: 0.8791 - acc: 0.9448 - val_loss: 2.0635 - val_acc: 0.8228

Epoch 00035: val_loss did not improve from 2.00610
Epoch 36/60
6680/6680 [==============================] - 4s 562us/step - loss: 0.8757 - acc: 0.9448 - val_loss: 2.0421 - val_acc: 0.8192

Epoch 00036: val_loss did not improve from 2.00610
Epoch 37/60
6680/6680 [==============================] - 4s 553us/step - loss: 0.8470 - acc: 0.9437 - val_loss: 2.1251 - val_acc: 0.8120

Epoch 00037: val_loss did not improve from 2.00610
Epoch 38/60
6680/6680 [==============================] - 4s 552us/step - loss: 0.8051 - acc: 0.9472 - val_loss: 2.0063 - val_acc: 0.8144

Epoch 00038: val_loss did not improve from 2.00610
Epoch 39/60
6680/6680 [==============================] - 4s 549us/step - loss: 0.8027 - acc: 0.9473 - val_loss: 1.9708 - val_acc: 0.8204

Epoch 00039: val_loss improved from 2.00610 to 1.97083, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 40/60
6680/6680 [==============================] - 4s 547us/step - loss: 0.7936 - acc: 0.9478 - val_loss: 2.0139 - val_acc: 0.8204

Epoch 00040: val_loss did not improve from 1.97083
Epoch 41/60
6680/6680 [==============================] - 4s 551us/step - loss: 0.7864 - acc: 0.9484 - val_loss: 2.0775 - val_acc: 0.8192

Epoch 00041: val_loss did not improve from 1.97083
Epoch 42/60
6680/6680 [==============================] - 4s 550us/step - loss: 0.7844 - acc: 0.9488 - val_loss: 2.0225 - val_acc: 0.8180

Epoch 00042: val_loss did not improve from 1.97083
Epoch 43/60
6680/6680 [==============================] - 4s 546us/step - loss: 0.7800 - acc: 0.9497 - val_loss: 2.0225 - val_acc: 0.8108

Epoch 00043: val_loss did not improve from 1.97083
Epoch 44/60
6680/6680 [==============================] - 4s 542us/step - loss: 0.7762 - acc: 0.9493 - val_loss: 1.9826 - val_acc: 0.8240

Epoch 00044: val_loss did not improve from 1.97083
Epoch 45/60
6680/6680 [==============================] - 4s 549us/step - loss: 0.7804 - acc: 0.9488 - val_loss: 1.9799 - val_acc: 0.8311

Epoch 00045: val_loss did not improve from 1.97083
Epoch 46/60
6680/6680 [==============================] - 4s 543us/step - loss: 0.7775 - acc: 0.9504 - val_loss: 1.9916 - val_acc: 0.8168

Epoch 00046: val_loss did not improve from 1.97083
Epoch 47/60
6680/6680 [==============================] - 4s 564us/step - loss: 0.7739 - acc: 0.9507 - val_loss: 2.0287 - val_acc: 0.8228

Epoch 00047: val_loss did not improve from 1.97083
Epoch 48/60
6680/6680 [==============================] - 4s 553us/step - loss: 0.7760 - acc: 0.9503 - val_loss: 1.9795 - val_acc: 0.8204

Epoch 00048: val_loss did not improve from 1.97083
Epoch 49/60
6680/6680 [==============================] - 4s 557us/step - loss: 0.7762 - acc: 0.9503 - val_loss: 1.9514 - val_acc: 0.8251

Epoch 00049: val_loss improved from 1.97083 to 1.95140, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 50/60
6680/6680 [==============================] - 4s 556us/step - loss: 0.7706 - acc: 0.9513 - val_loss: 2.0270 - val_acc: 0.8251

Epoch 00050: val_loss did not improve from 1.95140
Epoch 51/60
6680/6680 [==============================] - 4s 547us/step - loss: 0.7685 - acc: 0.9515 - val_loss: 2.0531 - val_acc: 0.8263

Epoch 00051: val_loss did not improve from 1.95140
Epoch 52/60
6680/6680 [==============================] - 4s 560us/step - loss: 0.7729 - acc: 0.9513 - val_loss: 2.0031 - val_acc: 0.8228

Epoch 00052: val_loss did not improve from 1.95140
Epoch 53/60
6680/6680 [==============================] - 4s 556us/step - loss: 0.7736 - acc: 0.9503 - val_loss: 1.9764 - val_acc: 0.8240

Epoch 00053: val_loss did not improve from 1.95140
Epoch 54/60
6680/6680 [==============================] - 4s 562us/step - loss: 0.7685 - acc: 0.9515 - val_loss: 2.0284 - val_acc: 0.8216

Epoch 00054: val_loss did not improve from 1.95140
Epoch 55/60
6680/6680 [==============================] - 4s 573us/step - loss: 0.7713 - acc: 0.9510 - val_loss: 2.0013 - val_acc: 0.8311

Epoch 00055: val_loss did not improve from 1.95140
Epoch 56/60
6680/6680 [==============================] - 4s 571us/step - loss: 0.7725 - acc: 0.9506 - val_loss: 2.0785 - val_acc: 0.8156

Epoch 00056: val_loss did not improve from 1.95140
Epoch 57/60
6680/6680 [==============================] - 4s 551us/step - loss: 0.7726 - acc: 0.9512 - val_loss: 2.0447 - val_acc: 0.8132

Epoch 00057: val_loss did not improve from 1.95140
Epoch 58/60
6680/6680 [==============================] - 4s 558us/step - loss: 0.7705 - acc: 0.9518 - val_loss: 2.0905 - val_acc: 0.8216

Epoch 00058: val_loss did not improve from 1.95140
Epoch 59/60
6680/6680 [==============================] - 4s 556us/step - loss: 0.7725 - acc: 0.9509 - val_loss: 2.0568 - val_acc: 0.8120

Epoch 00059: val_loss did not improve from 1.95140
Epoch 60/60
6680/6680 [==============================] - 4s 558us/step - loss: 0.7683 - acc: 0.9516 - val_loss: 2.0343 - val_acc: 0.8228

Epoch 00060: val_loss did not improve from 1.95140
Out[84]:
<keras.callbacks.History at 0x7fc02fe376a0>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [85]:
### TODO: Load the model weights with the best validation loss.
InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [86]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) \
                           for feature in test_inceptionv3]

# report test accuracy
test_accuracy = 100*np.sum(np.array(InceptionV3_predictions)==\
                           np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 79.1866%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [45]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *

def InceptionV3_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_InceptionV3(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = InceptionV3_model.predict(bottleneck_feature)
    prediction = predicted_vector[0]
    
    breeds_predicted = [dog_names[idx] for idx in np.argsort(prediction)[::-1][:top_N]]
    confidence_predicted = np.sort(prediction)[::-1][:top_N]
    
    # return dog breed that is predicted by the model
    return breeds_predicted, confidence_predicted
In [46]:
InceptionV3_predict_breed(train_files[2])
Out[46]:
(['n/088.Irish_water_spaniel', 'n/035.Boykin_spaniel', 'n/053.Cocker_spaniel'],
 array([9.94461298e-01, 5.52559597e-03, 1.29119835e-05], dtype=float32))
In [47]:
VGG16_predict_breed(train_files[2])
Out[47]:
(['n/088.Irish_water_spaniel', 'n/053.Cocker_spaniel', 'n/124.Poodle'],
 array([9.9993801e-01, 6.1804814e-05, 1.7565404e-07], dtype=float32))
In [48]:
show_image(train_files[2])
showing an image at data/dog_images/train/088.Irish_water_spaniel/Irish_water_spaniel_06014.jpg

Let's do a bit more thorough testing

In [49]:
human_files_set = human_files[:1000]
dog_files_set = train_files[:1000]
In [59]:
### Test dog_detector
dog_detected_counter = 0
ctr = 0
erroneous_dogs_in_humans = []
for human_filename in human_files_set:
    if dog_detector(human_filename):
        dog_detected_counter = dog_detected_counter + 1
        erroneous_dogs_in_humans.append(ctr)
    ctr = ctr + 1    
print(" > detected " + str(dog_detected_counter) + " dogs out of " + str(len(human_files_set)) +
      " human images, i.e. " + "{0:.2f}%".format(dog_detected_counter/len(human_files_set) * 100))
print(" > erroneous dog detection at: ", erroneous_dogs_in_humans)

dog_detected_counter = 0
ctr = 0
erroneous_dogs = []
for dog_filename in dog_files_set:
    if dog_detector(dog_filename):
        dog_detected_counter = dog_detected_counter + 1
    else:
        erroneous_dogs.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(dog_detected_counter) + " dogs out of " + str(len(dog_files_set)) +
      " dog images, i.e. " + "{0:.2f}%".format(dog_detected_counter/len(dog_files_set) * 100))
print(" > can't detect dogs at: ", erroneous_dogs)
 > detected 14 dogs out of 1000 human images, i.e. 1.40%
 > erroneous dog detection at:  [9, 114, 148, 177, 285, 344, 402, 422, 426, 438, 635, 684, 769, 952]
 > detected 984 dogs out of 1000 dog images, i.e. 98.40%
 > can't detect dogs at:  [146, 162, 242, 313, 322, 400, 480, 529, 530, 578, 654, 690, 755, 808, 965, 991]
In [60]:
show_image(human_files_set[erroneous_dogs_in_humans[2]])
showing an image at data/lfw/Carlos_De_Abreu/Carlos_De_Abreu_0001.jpg
In [61]:
show_image(dog_files_set[erroneous_dogs[2]])
showing an image at data/dog_images/train/067.Finnish_spitz/Finnish_spitz_04678.jpg
In [51]:
### Test human face detector, v1

face_detected_counter = 0
ctr = 0
erroneous_faces = []
for human_filename in human_files_set:
    if face_detector(human_filename):
        face_detected_counter = face_detected_counter + 1
    else:
        erroneous_faces.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " faces out of " + str(len(human_files_set)) +
      ", i.e. " + "{0:.2f}%".format(face_detected_counter/len(human_files_set) * 100))
print(" > cant detect face at: ", erroneous_faces)

face_detected_counter = 0
ctr = 0
erroneous_faces_in_dogs = []
for dog_filename in dog_files_set:
    if face_detector(dog_filename):
        face_detected_counter = face_detected_counter + 1
        erroneous_faces_in_dogs.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " human faces out of " + str(len(dog_files_set)) +
      " dog images, i.e. " + "{0:.2f}%".format(face_detected_counter/len(dog_files_set) * 100))
print(" > erroneously detected face at: ", erroneous_faces_in_dogs)
 > detected 983 faces out of 1000, i.e. 98.30%
 > cant detect face at:  [88, 195, 249, 360, 428, 448, 453, 481, 613, 640, 643, 660, 796, 798, 894, 915, 923]
 > detected 115 human faces out of 1000 dog images, i.e. 11.50%
 > erroneously detected face at:  [0, 14, 15, 21, 22, 23, 24, 30, 32, 37, 63, 78, 100, 111, 129, 132, 136, 138, 139, 140, 144, 153, 165, 174, 179, 181, 193, 215, 223, 224, 234, 242, 254, 262, 267, 268, 279, 303, 321, 323, 346, 359, 365, 367, 375, 376, 388, 398, 409, 415, 417, 423, 426, 429, 430, 442, 449, 460, 467, 487, 490, 500, 501, 502, 514, 560, 561, 568, 582, 589, 593, 617, 620, 630, 631, 647, 654, 666, 671, 672, 718, 728, 729, 741, 744, 763, 776, 779, 782, 792, 797, 805, 807, 815, 830, 844, 856, 863, 865, 877, 881, 891, 893, 905, 907, 912, 915, 934, 947, 954, 972, 978, 979, 985, 991]
In [52]:
### Test human face detector, v2

face_detected_counter = 0
ctr = 0
erroneous_faces = []
for human_filename in human_files_set:
    if face_detector2(human_filename):
        face_detected_counter = face_detected_counter + 1
    else:
        erroneous_faces.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " faces out of " + str(len(human_files_set)) +
      ", i.e. " + "{0:.2f}%".format(face_detected_counter/len(human_files_set) * 100))
print(" > cant detect face at: ", erroneous_faces)

face_detected_counter = 0
ctr = 0
erroneous_faces_in_dogs = []
for dog_filename in dog_files_set:
    if face_detector2(dog_filename):
        face_detected_counter = face_detected_counter + 1
        erroneous_faces_in_dogs.append(ctr)
    ctr = ctr + 1
print(" > detected " + str(face_detected_counter) + " human faces out of " + str(len(dog_files_set)) +
      " dog images, i.e. " + "{0:.2f}%".format(face_detected_counter/len(dog_files_set) * 100))
print(" > erroneously detected face at: ", erroneous_faces_in_dogs)
 > detected 1000 faces out of 1000, i.e. 100.00%
 > cant detect face at:  []
 > detected 46 human faces out of 1000 dog images, i.e. 4.60%
 > erroneously detected face at:  [23, 27, 132, 138, 140, 153, 166, 193, 207, 215, 262, 267, 268, 279, 303, 353, 375, 415, 417, 429, 430, 435, 455, 467, 484, 556, 560, 598, 630, 647, 744, 766, 778, 802, 863, 865, 866, 905, 915, 939, 954, 961, 972, 977, 985, 990]
In [77]:
### whatup MTCNN
show_image(dog_files_set[erroneous_faces_in_dogs[18]])
showing an image at data/dog_images/train/083.Ibizan_hound/Ibizan_hound_05652.jpg

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [54]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

def make_prediction(path, multiple_breeds = False):
    img = mpimg.imread(path)
    plt.axis('off')
    imgplot = plt.imshow(img)
    breeds, confidence = InceptionV3_predict_breed(path)
    # we would use the dog_detector function as it's more accurate
    # first check for dogs, if there are no dogs -- check for humans
    found_dog = dog_detector(path)
    found_face = face_detector2(path)
    if found_face:
        if found_dog:
            print("Hello! Woof woof!")
            print("Seems like a hooman and a dog... The dog looks like " + 
                  "a {}.".format(breeds[0].replace("_", " ")))
        else:
            print("Hello hooman!")
            print("If you were a dog, you\'d be a {}.".format(breeds[0].replace("_", " ")))
            
    elif found_dog:
            print("Woof woof!")
            print("You look like a {}.".format(breeds[0].replace("_", " ")))
    else:
        raise ValueError("Could not detect dogs or hoomans in the image.")

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: I think it works with a pretty decent performance for something I can run on my laptop. I really like this project and enjoyed it very much. I like that I was able to write a wrapper which says that there is a dog and a hooman! Potentially: (1) it can be useful to detect multiple dogs and characterize them, in a way the second human face detector (MTCNN) works, (2) would be nice to outline dog faces as well, (3) I think I'd need to try yet another face detector to improve the whole thing accuracy by voting or something... or to use a threshold in MTCNN to reduce human face detection in dog images... Se the performance comparison on a 1000 of images above...

In [55]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
In [97]:
make_prediction(dog_files_set[erroneous_faces_in_dogs[5]])
Hello! Woof woof!
Seems like a hooman and a dog... The dog looks like a n/071.German shepherd dog.
In [98]:
make_prediction("data/dog_images/train/015.Basset_hound/Basset_hound_01112.jpg")
Hello! Woof woof!
Seems like a hooman and a dog... The dog looks like a n/015.Basset hound.
In [99]:
make_prediction("my_images/internet_dawg1.jpg")
Woof woof!
You look like a n/056.Dachshund.
In [100]:
make_prediction("my_images/internet_dawg2.jpg")
Woof woof!
You look like a n/016.Beagle.
In [101]:
make_prediction("my_images/internet_dawg3.jpg")
Woof woof!
You look like a n/046.Cavalier king charles spaniel.
In [102]:
make_prediction("my_images/internet_dawg4.jpg")
Woof woof!
You look like a n/029.Border collie.
In [103]:
make_prediction("my_images/internet_dawg5.jpg")
Woof woof!
You look like a n/049.Chinese crested.
In [104]:
make_prediction("my_images/internet_dawg6.jpg")
Woof woof!
You look like a n/056.Dachshund.
In [105]:
make_prediction(dog_files_short[erroneous_dogs_faces[1]])
Hello! Woof woof!
Seems like a hooman and a dog... The dog looks like a n/005.Alaskan malamute.

Some people

In [106]:
make_prediction("my_images/pavel.jpg")
Hello hooman!
If you were a dog, you'd be a n/056.Dachshund.
In [107]:
make_prediction("my_images/dasha.jpg")
Hello hooman!
If you were a dog, you'd be a n/038.Brussels griffon.

The Good Wife cast

In [108]:
make_prediction("my_images/Julianna_Margulies.jpg")
Hello hooman!
If you were a dog, you'd be a n/056.Dachshund.
In [109]:
make_prediction("my_images/Chris_Noth.jpg")
Hello hooman!
If you were a dog, you'd be a n/049.Chinese crested.
In [110]:
make_prediction("my_images/Josh_Charles.jpg")
Hello hooman!
If you were a dog, you'd be a n/039.Bull terrier.
In [111]:
make_prediction("my_images/Christine_Baranski_at_Met_Opera_cropped.jpg")
Hello hooman!
If you were a dog, you'd be a n/056.Dachshund.
In [112]:
make_prediction("my_images/Carrie_Preston.jpg")
---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1311       return self._call_tf_sessionrun(
-> 1312           options, feed_dict, fetch_list, target_list, run_metadata)
   1313 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1419             self._session, options, feed_dict, fetch_list, target_list,
-> 1420             status, run_metadata)
   1421 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
    515             compat.as_text(c_api.TF_Message(self.status.status)),
--> 516             c_api.TF_GetCode(self.status.status))
    517     # Delete the underlying status object from memory otherwise it stays alive

InternalError: Dst tensor is not initialized.
	 [[Node: _arg_Placeholder_13914_0_340/_110549 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_1811__arg_Placeholder_13914_0_340", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]

During handling of the above exception, another exception occurred:

InternalError                             Traceback (most recent call last)
<ipython-input-112-3119661ef9e4> in <module>()
----> 1 make_prediction("my_images/Carrie_Preston.jpg")

<ipython-input-54-8ea1f0f39088> in make_prediction(path, multiple_breeds)
      8     plt.axis('off')
      9     imgplot = plt.imshow(img)
---> 10     breeds, confidence = InceptionV3_predict_breed(path)
     11     # we would use the dog_detector function as it's more accurate
     12     # first check for dogs, if there are no dogs -- check for humans

<ipython-input-45-c638c920583f> in InceptionV3_predict_breed(img_path)
      5 def InceptionV3_predict_breed(img_path):
      6     # extract bottleneck features
----> 7     bottleneck_feature = extract_InceptionV3(path_to_tensor(img_path))
      8     # obtain predicted vector
      9     predicted_vector = InceptionV3_model.predict(bottleneck_feature)

~/git/dog-project/extract_bottleneck_features.py in extract_InceptionV3(tensor)
     17 def extract_InceptionV3(tensor):
     18         from keras.applications.inception_v3 import InceptionV3, preprocess_input
---> 19         return InceptionV3(weights='imagenet', include_top=False).predict(preprocess_input(tensor))

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/applications/inception_v3.py in InceptionV3(include_top, weights, input_tensor, input_shape, pooling, classes)
    389                 cache_subdir='models',
    390                 file_hash='bcbd6486424b2319ff4ef7d526e38f63')
--> 391         model.load_weights(weights_path)
    392     elif weights is not None:
    393         model.load_weights(weights)

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/topology.py in load_weights(self, filepath, by_name, skip_mismatch, reshape)
   2665             else:
   2666                 load_weights_from_hdf5_group(
-> 2667                     f, self.layers, reshape=reshape)
   2668 
   2669     def _updated_config(self):

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/engine/topology.py in load_weights_from_hdf5_group(f, layers, reshape)
   3391                              ' elements.')
   3392         weight_value_tuples += zip(symbolic_weights, weight_values)
-> 3393     K.batch_set_value(weight_value_tuples)
   3394 
   3395 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in batch_set_value(tuples)
   2375             assign_ops.append(assign_op)
   2376             feed_dict[assign_placeholder] = value
-> 2377         get_session().run(assign_ops, feed_dict=feed_dict)
   2378 
   2379 

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    903     try:
    904       result = self._run(None, fetches, feed_dict, options_ptr,
--> 905                          run_metadata_ptr)
    906       if run_metadata:
    907         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1138     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1139       results = self._do_run(handle, final_targets, final_fetches,
-> 1140                              feed_dict_tensor, options, run_metadata)
   1141     else:
   1142       results = []

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1319     if handle is None:
   1320       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1321                            run_metadata)
   1322     else:
   1323       return self._do_call(_prun_fn, handle, feeds, fetches)

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1338         except KeyError:
   1339           pass
-> 1340       raise type(e)(node_def, op, message)
   1341 
   1342   def _extend_graph(self):

InternalError: Dst tensor is not initialized.
	 [[Node: _arg_Placeholder_13914_0_340/_110549 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_1811__arg_Placeholder_13914_0_340", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]

Sneaky cats

In [90]:
make_prediction("my_images/pepe.jpg")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-90-26a4216d066c> in <module>()
----> 1 make_prediction("my_images/pepe.jpg")

<ipython-input-54-8ea1f0f39088> in make_prediction(path, multiple_breeds)
     26             print("You look like a {}.".format(breeds[0].replace("_", " ")))
     27     else:
---> 28         raise ValueError("Could not detect dogs or hoomans in the image.")

ValueError: Could not detect dogs or hoomans in the image.
In [93]:
make_prediction("my_images/totoro.jpg")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-93-0fbaf63cd363> in <module>()
----> 1 make_prediction("my_images/totoro.jpg")

<ipython-input-54-8ea1f0f39088> in make_prediction(path, multiple_breeds)
     26             print("You look like a {}.".format(breeds[0].replace("_", " ")))
     27     else:
---> 28         raise ValueError("Could not detect dogs or hoomans in the image.")

ValueError: Could not detect dogs or hoomans in the image.

Please download your notebook to submit